import time

from .trigger import AlertTrigger


# 联动进入报警器
class StayTrigger(AlertTrigger):

    def __init__(self, event, object, region, threshhold=None):
        super().__init__(event, object, region)
        assert threshhold is not None, '必须传入时间阈值参数'
        assert threshhold > 0, '时间阈值必须大于0'
        self._threshhold = threshhold
        self._stay_objects = {}  # 存储所有目前留在画面上的物体
    
    def enter(self, obj, objs, image):
        self._stay_objects[obj.id] = obj

    def update(self, objs, image):
        for obj in tuple(self._stay_objects.values()):
            if obj.current_time - obj.create_time >= self._threshhold:
                self._alert([obj], obj.make_shotcut())
                self._stay_objects.pop(obj.id)

    def leave(self, obj, objs, image):
        self._stay_objects.pop(obj.id, None)  # 这里给个默认值是因为这个obj可能被update删了
